package cn.zjnu.aop;

import cn.zjnu.dao.LoginDao;
import cn.zjnu.domain.User;
import cn.zjnu.service.LoginService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect                    //告知Spring这是 AOP 文件
@EnableAspectJAutoProxy    //告知spring这是由 注解 开发的AOP
public class LoginAdvice {
    @Autowired
    private LoginService loginService;
    @Autowired
    private LoginDao loginDao;
    //    创建切入点
    /*
        1. 注册方法的切入点
            通过AOP对其功能进行增强
    */
    @Pointcut("execution(* cn.zjnu.service.impl.LoginServiceImpl.signUp(..))")
    private void Aop_signUp(){}
    @Pointcut("execution(* cn.zjnu.service.impl.LoginServiceImpl.changePassword(..))")
    private void Aop_ChangePassword(){}




    @Around("Aop_signUp()")
    public Object aroundAop_signUp(ProceedingJoinPoint pjp) throws Throwable{
        Object[] args = pjp.getArgs();
        User user = (User)args[0];
        boolean sameName = loginService.checkRename(user);
        System.out.println("LoginAdvice:sameName = " + sameName+" , and username = " + user.getUsername());
        if (sameName){
            user.setUsername("errorName");
        }
        Object ret = pjp.proceed(args);
        return ret;
    }
    @Around("Aop_ChangePassword()")
    public Object aroundAop_ChangePassword(ProceedingJoinPoint pjp) throws Throwable{
        Object[] args = pjp.getArgs();
        User before = (User) args[0];
        User after = (User) args[1];
        System.out.println("before : " + before);
        System.out.println("after : " + after);
        User userTemp = loginDao.SelectByNamePassword(before);
        if(userTemp != null){ //用户信息匹配
            before.setPassword(after.getPassword());
            loginDao.update(before);
        }
        Object ret = pjp.proceed(args);
        return ret;
    }

}
